package cn.kinoko.service.manga.impl;

import cn.kinoko.common.aspect.annotation.Cacheable;
import cn.kinoko.common.base.model.BaseServiceImpl;
import cn.kinoko.common.constant.CacheKeyConstant;
import cn.kinoko.common.utils.BeanHelper;
import cn.kinoko.mapper.manga.MangaEpCookedMapper;
import cn.kinoko.model.manga.entity.MangaEpCooked;
import cn.kinoko.model.manga.vo.MangaEpCookedVO;
import cn.kinoko.model.manga.vo.MangaEpImgVO;
import cn.kinoko.service.common.util.ThumbPathHelper;
import cn.kinoko.service.manga.MangaEpCookedService;
import cn.kinoko.service.minio.MinioService;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kinoko
 */
@Service
public class MangaEpCookedServiceImpl extends BaseServiceImpl<MangaEpCookedMapper, MangaEpCooked> implements MangaEpCookedService {
    @Resource
    private MinioService minioService;

    /**
     * 根据章节id删除所有页码
     * @param epId 章节id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delByEpId(Long epId) {
        delById(MangaEpCooked::getEpId, epId);
    }

    /**
     * 根据漫画id删除所有页码
     * @param mangaId 漫画id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delByMangaId(Long mangaId) {
        delById(MangaEpCooked::getMangaId, mangaId);
    }

    /**
     * 根据id删除所有页码
     * @param column 业务字段
     * @param id     业务id
     */
    private void delById(SFunction<MangaEpCooked, ?> column, Long id) {
        List<String> cookedUrlList = lambdaQuery().eq(column, id).list()
                .stream().map(MangaEpCooked::getImageUrl).toList();
        if (!cookedUrlList.isEmpty()) {
            // 删除漫画页码
            lambdaUpdate().eq(column, id).remove();
            // 取消minio文件的引用
            minioService.deleteFileReference(cookedUrlList);
        }
    }

    /**
     * 根据章节id查询所有页码
     * @param epId 章节id
     * @return 漫画页码
     */
    @Cacheable(key = CacheKeyConstant.EP_COOKED_IMG_LIST, params = "#epId")
    @Override
    public List<MangaEpCookedVO> queryList(Long epId) {
        return lambdaQuery()
                .eq(MangaEpCooked::getEpId, epId)
                .orderByAsc(MangaEpCooked::getNumber)
                .list().stream()
                .map(mangaRaw -> {
                    MangaEpCookedVO mangaEpRawVO = BeanHelper.copyProperties(mangaRaw, MangaEpCookedVO.class);
                    ThumbPathHelper.toThumbPath(mangaEpRawVO, MangaEpImgVO::getImageUrl, MangaEpImgVO::setThumbUrl);
                    return mangaEpRawVO;
                })
                .collect(Collectors.toList());
    }
}
